import json
from django.http import JsonResponse
from rest_framework.views import APIView
from .models import LogError
from .serializers import ErrorListSerializer, ErrorDetailSerializer
from utils.utils import responseSuccess, responseError, serializerJSON, filterFields, MyPaginator

# 错误日志列表数据
class ErrorListAPI(APIView):
    def get(self,req):
        queryDict = req.query_params.dict()
        filterDict = filterFields(LogError, queryDict, allow=['createTimeRange'])
        if createTimeRange := filterDict.pop('createTimeRange',None):
            filterDict['createTime__range'] = json.loads(createTimeRange)
        users = LogError.objects.filter(**filterDict)
        paginator = MyPaginator(users, **queryDict)
        serializers = ErrorListSerializer(paginator.object_list, many=True)
        datas = serializerJSON(serializers)
        data = paginator.data(datas)
        return JsonResponse(responseSuccess(data), safe=False)
    
# 错误日志详情数据
class ErrorDetailAPI(APIView):
    def get(self, req):
        id = req.query_params.dict().get("id")
        if not id:
            return JsonResponse(responseError('id不能为空'), safe=False)
        serializer = ErrorDetailSerializer(LogError.objects.get(pk=id))
        return JsonResponse(responseSuccess(serializer.data), safe=False)
    

